<?php
require 'db.php'; // 包含数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}

// 获取当前用户发布的已批准的文章
$stmt = $conn->prepare("SELECT id, title, author, created_at FROM articles WHERE author = ? AND status = 'approved' ORDER BY created_at DESC");
$stmt->bind_param("s", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$articles = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $articles[] = $row;
    }
}

$stmt->close();

// 返回JSON格式的文章列表
header('Content-Type: application/json');
echo json_encode(['articles' => $articles]);

$conn->close();
?>

